<template>
  <section class="todoapp">
    <!-- 头部部分 -->
    <TodoHeader @addList="addList"></TodoHeader>
    <!-- 主体部分 -->
    <TodoMain
      :list="renderList"
      @change="change"
      @delList="delList"
      :checkbox="checkbox"
      @isAll="isAll"
    ></TodoMain>
    <!-- 底部部分 -->
    <TodoFoot
      @clearDoneList="clearDoneList"
      :isDoneClear="isDoneClear"
      :allIsShow="allIsShow"
      v-show="list.length"
      @changeType="changeType"
      :type="type"
    ></TodoFoot>
  </section>
</template>

<script>
import TodoHeader from '@/components/TodoHeader.vue'
import TodoMain from '@/components/TodoMain.vue'
import TodoFoot from '@/components/TodoFoot.vue'
export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFoot,
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem('todoList')) || [],
      type: 'all',
    }
  },
  methods: {
    //改变状态功能
    change(id) {
      const res = this.list.find((item) => item.id === id)
      res.isDone = !res.isDone
    },
    //删除功能
    delList(id) {
      this.list = this.list.filter((item) => item.id !== id)
    },
    //添加功能
    addList(message) {
      const obj = { id: +new Date(), name: message, isDone: false }
      this.list = [obj, ...this.list]
    },
    //清除已完成
    clearDoneList() {
      this.list = this.list.filter((item) => item.isDone === false)
    },
    changeType(type) {
      this.type = type
    },
    isAll(bl) {
      this.list.forEach((item) => (item.isDone = bl))
    },
  },
  computed: {
    isDoneClear() {
      return this.list.some((item) => item.isDone)
    },
    allIsShow() {
      return this.list.filter((item) => item.isDone === false).length
    },
    renderList() {
      switch (this.type) {
        case 'all':
          return this.list
        case 'active':
          return this.list.filter((item) => item.isDone === false)
        case 'completed':
          return this.list.filter((item) => item.isDone)
        default:
          return this.list
      }
    },
    checkbox() {
      return this.list.every((item) => item.isDone)
    },
  },
  watch: {
    list: {
      deep: true,
      handler(newValue) {
        localStorage.setItem('todoList', JSON.stringify(newValue))
      },
    },
  },
}
</script>

<style></style>
